#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
"""
@contact: wangdali215@163.com
@file: cleardisk.py
"""

import os
import sys
import re
import datetime
import time
import logging
import fnmatch

# 脚本根目录
BASEDIR = os.path.split(os.path.realpath(__file__))[0]
NOWTIME = datetime.datetime.now().strftime('%Y%m%d%H%M%S')


class Logger:
    def __init__(self, logname, logfile):
        self._logger = logging.getLogger(logname)
        handler = logging.FileHandler(logfile)
        formatter = logging.Formatter('%(asctime)s %(filename)s %(funcName)s %(lineno)d %(message)s')
        handler.setFormatter(formatter)
        self._logger.addHandler(handler)
        self._logger.setLevel(logging.INFO)

    def log(self, msg):
        if self._logger is not None:
            self._logger.info(msg)

# 定义删除日志文件
rmfilelog = Logger("rmfilelog", BASEDIR + os.sep + 'logs/' + NOWTIME + 'rmfile.log')


def dir_list_file(path, filetype):
    for root, dirs, files in os.walk(path):
        for basename in files:
            if fnmatch.fnmatch(basename, filetype):
                filename = os.path.join(root, basename)
                yield filename


def delete_disk(p_time, p_dir, p_file):
    _data = int(filter(str.isdigit, p_time))
    if bool(re.search('m', p_time, re.IGNORECASE)):
        _t = (datetime.datetime.now()-datetime.timedelta(minutes=_data)).strftime("%Y-%m-%d %H:%M:%S")
    elif bool(re.search('h', p_time, re.IGNORECASE)):
        _t = (datetime.datetime.now()-datetime.timedelta(hours=_data)).strftime("%Y-%m-%d %H:%M:%S")
    elif bool(re.search('d', p_time, re.IGNORECASE)):
        _t = (datetime.datetime.now()-datetime.timedelta(days=_data)).strftime("%Y-%m-%d %H:%M:%S")
    _timestamps = int(time.mktime(time.strptime(_t, "%Y-%m-%d %H:%M:%S")))
    for filepath in dir_list_file(p_dir, p_file):
        if int(str(os.path.getmtime(filepath)).split('.')[0]) <= _timestamps:
            os.remove(filepath)
            rmfilelog.log('删除日志: ' + filepath)


def clear_disk(p_size, p_dir, p_file):
    _data = int(filter(str.isdigit, p_size))
    if bool(re.search('k', p_size, re.IGNORECASE)):
        p_size = _data
    elif bool(re.search('m', p_size, re.IGNORECASE)):
        p_size = _data * 1024
    elif bool(re.search('g', p_size, re.IGNORECASE)):
        p_size = _data * 1024 * 1024
    for filepath in dir_list_file(p_dir, p_file):
        if int(os.path.getsize(filepath)) > int(p_size):
            f = open(filepath, 'w+')
            f.truncate()
            f.close()
            rmfilelog.log('清空日志: ' + filepath)

confile_path = os.path.split(os.path.realpath(__file__))[0] + os.sep + 'disk.ini'
tmpfile_path = '/tmp/diskfile'

if not os.path.isfile(confile_path):
    print '''
    请在脚本所在目录建立配置文件disk.ini, 格式如下:

    #a 删除文件:delete <天数d|小时h|分钟m> <文件所在目录> <文件名>
    #b 清空文件:clear  <文件大小k|m|g> <文件所在目录> <文件名>
    # 文件所在目录，文件名支持通配符

    delete	2h	/Users/*/html/	*.zip
    clear	2332K	/Users/wangdali/*/hplus*/	*.html
    '''
    sys.exit(1)

confile = open(name=confile_path, mode='r')
tmpfile = open(name=tmpfile_path, mode='w')
for line in confile.readlines():
    line = line.lstrip()
    if line.startswith('#') or not line.split():
        continue
    tmpfile.write(line)
confile.close()
tmpfile.close()

tmpfile = open(name=tmpfile_path, mode='r')
regex = re.compile('\s+')
for line in tmpfile.readlines():
    linelist = regex.split(line)
    if linelist[0] == 'delete':
        delete_disk(linelist[1], linelist[2], linelist[3])
    elif linelist[0] == 'clear':
        clear_disk(linelist[1], linelist[2], linelist[3])
tmpfile.close()
